package com.etc.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baidu.ai.aip.solution.ImgCensor;
import com.etc.entity.Audit;
import com.etc.entity.Files;
import com.etc.entity.User;
import com.etc.service.AuditService;
import com.etc.service.FileService;
import com.etc.util.CommenMassage;

/**
 * 单文件上传的控制器
 * 
 * @author cyf
 *
 */
@Controller
public class FileUploadController {
	// 用于返回处理信息的类
	@Autowired
	private CommenMassage msg;
	// 处理文件操作的Service类
	@Autowired
	private FileService fileService;
	@Autowired
	private AuditService auditService;

	/**
	 * 
	 * @param upload_file
	 *            上传的文件
	 * @param secondid
	 *            执行上传操作时所在的目录id
	 * @param session
	 * @return 返回文件处理信息
	 */
	@RequestMapping(value = "fileupload", method = RequestMethod.POST)
	@ResponseBody
	public CommenMassage fileUpload(@RequestParam("upload_file") MultipartFile upload_file, String secondid,
			HttpSession session) {
		// 把获取的目录id转成int类型便于保存数据库
		int secondId = Integer.parseInt(secondid);
		// 得到文件名，包含文件后缀
		String fileName = new Date().getTime() + upload_file.getOriginalFilename();
		// 得到去除后缀的文件名
		String allfileName = fileName.substring(0, fileName.lastIndexOf("."));
		// 文件大小的判断
		Long size = upload_file.getSize();
		int length = (size).toString().length();
		String fileSize = "";
		double a = size.doubleValue();
		if (length >= 4 && length <= 6) {
			fileSize = String.format("%.2f", a / 1024) + "KB";
		} else if (length >= 7 && length <= 10) {
			fileSize = String.format("%.2f", a / 1024 / 1024) + "M";
		} else if (length <= 3) {
			fileSize = a + "B";
		} else {
			fileSize = String.format("%.2f", a / 1024 / 1024 / 1024) + "G";
		}
		// String fileSize=Long.toString(upload_file.getSize());
		// 文件存储路径
		String filePath = "";
		// 上传者的信息
		User user = (User) session.getAttribute("user");
		// 得到文件的类型
		String type = upload_file.getContentType();
		System.out.println(type);
		// 如果上传的是图片类型，调用接口进行审核
		if (type.equals("image/png") || type.equals("image/jpeg") || type.equals("image/gif")) {
			// String path="E:\\"+fileName;
			String path = "D:\\apache-tomcat-8.5.13-windows-x64\\apache-tomcat-8.5.13\\webapps\\files"
					+ user.getUserid() + "\\" + fileName;
			File newFile = new File(path);
			filePath = "http://192.168.11.242:8080/files" + user.getUserid() + "/" + fileName;
			try {
				// 执行存储动作
				upload_file.transferTo(newFile);
				String result = ImgCensor.checkImg(path);
				// 如果图片没有违规，则存储到数据库中
				if (result.equals("正常")) {
					Files file = new Files(0, allfileName, filePath, secondId, new Date().toLocaleString(), 4,
							user.getUserid(), fileSize);
					fileService.addFile(file);
					msg.setMsg("上传成功");
					// 这里要将文件存到为用户创建的指定目录下
				} else {
					msg.setMsg(result);
				}

			} catch (IllegalStateException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else if (type.equals("video/mp4") || type.equals("video/x-ms-wmv")) {
			// 将获取到的文件加上时间戳存到指定目录下等待管理员审核
			// 演示用的程剑服务器地址
			// String
			// path="D:\\apache-tomcat-8.5.13-windows-x64\\apache-tomcat-8.5.13\\webapps\\files\\"+new
			// Date().getTime()+upload_file.getOriginalFilename();
			String path = "D:\\apache-tomcat-8.5.13-windows-x64\\apache-tomcat-8.5.13\\webapps\\files"
					+ user.getUserid() + "\\" + fileName;
			File newFile = new File(path);
			filePath = "http://192.168.11.242:8080/files" + user.getUserid() + "/" + fileName;
			try {
				// 执行存储动作
				upload_file.transferTo(newFile);
				Audit file = new Audit(0, allfileName, filePath, secondId, new Date().toLocaleString(), 2,
						user.getUserid(), fileSize, 0);
				boolean flag = auditService.insertSelective(file);
				if (flag) {
					msg.setMsg("上传成功，等待审核");
				} else {
					msg.setMsg("上传失败");
				}

			} catch (IllegalStateException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if (type.equals("audio/mp3") || type.equals("text/plain") || type.equals("application/octet-stream")
				|| type.equals("application/x-msdownload")||type.equals("application/zip")) {
			String path = "D:\\apache-tomcat-8.5.13-windows-x64\\apache-tomcat-8.5.13\\webapps\\files"
					+ user.getUserid() + "\\" + fileName;
			File newFile = new File(path);
			filePath = "http://192.168.11.242:8080/files" + user.getUserid() + "/" + fileName;
			try {
				// 执行存储动作
				upload_file.transferTo(newFile);
				int fileType = 1;
				if (type.equals("text/plain") || type.equals("application/octet-stream")
						|| type.equals("application/x-msdownload")||type.equals("application/zip")) {
					fileType = 3;
				}
				Files file = new Files(0, allfileName, filePath, secondId, new Date().toLocaleString(), fileType,
						user.getUserid(), fileSize);
				int n = fileService.addFile(file);
				if (n > 0) {
					msg.setMsg("上传成功");
				} else {
					msg.setMsg("上传失败");
				}

			} catch (IllegalStateException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else {
			msg.setMsg("文件格式暂不支持");
		}

		return msg;
	}

}
